//
// Created by Administrator on 2020/7/2.
//

#include "JavaCallHelper.h"


JavaCallHelper::JavaCallHelper(JNIEnv *env, jobject thiz, JavaVM *javaVm) {
    this->javaVM = javaVm;
    this->env = env;

    this->instance = env->NewGlobalRef(thiz);

    jclass jclazz = env->GetObjectClass(instance);
    jvm_onPrepared = env->GetMethodID(jclazz, "onPrepared", "()V");
    jvm_onError = env->GetMethodID(jclazz, "onError", "(I)V");
}

JavaCallHelper::~JavaCallHelper() {
    javaVM = 0;
    env->DeleteGlobalRef(instance);
    instance = 0;
}

void JavaCallHelper::onError(int threadMode, int errorCode) {
    if (threadMode == THREAD_MAIN) {
        //主线程直接调用
        env->CallVoidMethod(instance, jvm_onError, errorCode);
    } else {//子线程
        //子线程的env
        JNIEnv *env_child;
        javaVM->AttachCurrentThread(&env_child, NULL);
        env_child->CallVoidMethod(instance, jvm_onError, errorCode);
        javaVM->DetachCurrentThread();
    }//end if
}

void JavaCallHelper::onPrepared(int threadMode) {
    if (threadMode == THREAD_MAIN) {
        //主线程直接调用
        env->CallVoidMethod(instance, jvm_onPrepared);
    } else {//子线程
        //子线程的env
        JNIEnv *env_child;
        javaVM->AttachCurrentThread(&env_child, NULL);
        env_child->CallVoidMethod(instance, jvm_onPrepared);
        javaVM->DetachCurrentThread();
    }//end if
}



